package org.sws.trigger.http;

import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;
import org.apache.zookeeper.data.Stat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.sws.trigger.api.IDCCService;
import org.sws.types.model.Response;

import java.nio.charset.StandardCharsets;

/**
 * @Author sws
 * @Date 2025/4/18 09:10
 * @description:
 */
@Slf4j
@RestController
@CrossOrigin("${app.config.cross-origin}")
@RequestMapping("/api/market/raffle/dcc")
public class DCCController implements IDCCService {

    private static final String BASE_CONFIG_PATH_CONFIG = "/big-market-dcc/config";

    @Autowired(required = false)
    private CuratorFramework client;

    /**
     * 更新zookeeper节点值
     */
    @GetMapping("updateConfig")
    @Override
    public Response<Boolean> updateConfig(String key, String value) throws Exception {

        String keyPath = BASE_CONFIG_PATH_CONFIG.concat("/").concat(key);
        try {
            if(null == client.checkExists().forPath(keyPath)){
                client.create().creatingParentsIfNeeded().forPath(keyPath);
                log.info("DCC 节点监听 base node {} not absent create new done!", keyPath);
            }
            Stat stat = client.setData().forPath(keyPath,value.getBytes(StandardCharsets.UTF_8));
            log.info("DCC 动态配置值变更完成 key:{} value:{} time:{}", key, value, stat.getCtime());
            return Response.success(Boolean.TRUE);
        } catch (Exception e) {
            log.info("DCC 动态配置值变更失败 key:{} value:{}", key, value);
            return Response.fail(e);
        }
    }
}
